package org.example;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;

public class Client {
    private static final Logger LOGGER = Logger.getLogger(Client.class);

    private final Server server;
    private volatile Certificate certificate;
    private final SecretKey secretKey;

    public Client(Server server) {
        this.server = server;
        secretKey = SecretKeyUtil.createDESKey();
    }

    /**
     * 发送请求
     * @param msg 请求数据内容
     * @return
     */
    public String request(String msg) {
        if (certificate == null || !certificate.isValid()) {
            synchronized (this) {
                if (certificate == null) {
                    certificate = server.getCertificate();
                    certificate.validateSign(decryptSign(certificate.getSign()));
                    LOGGER.info("检验签名成功");
                    server.registerSecretKey(this, encryptSecretKey(secretKey));
                    LOGGER.info("与服务端注册对称加密密钥成功");
                    certificate.setValid(true);
                }
            }
        }
        LOGGER.info(String.format("请求内容为[%s]", msg));
        // 加密msg
        byte[] encryptRequestData = SecretKeyUtil.encryptDES(secretKey, msg.getBytes(StandardCharsets.UTF_8));
        // 解密response
        byte[] response = server.response(this, encryptRequestData);
        byte[] decryptResponse = SecretKeyUtil.decryptDES(secretKey, response);
        String responseData = new String(decryptResponse, StandardCharsets.UTF_8);
        LOGGER.info(String.format("接收响应数据内容为[%s]", responseData));
        return responseData;
    }

    private String decryptSign(byte[] sign) {
        return new String(SecretKeyUtil.decryptRSA(CA.PUBLIC_KEY, sign), StandardCharsets.UTF_8);
    }

    private byte[] encryptSecretKey(SecretKey secretKey) {
        byte[] encodedSecretKey = secretKey.getEncoded();
        return SecretKeyUtil.encryptRSA(certificate.getPublicKey(), encodedSecretKey);
    }

}
